package com.wzh.product.service.impl;

import com.wzh.common.utils.JwtUtil;
import com.wzh.common.utils.R;
import com.wzh.product.entity.MydisEntity;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.product.dao.UserDao;
import com.wzh.product.entity.UserEntity;
import com.wzh.product.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    protected RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R login(Map<String, Object> params) {
        String tel = (String) params.get("tel");
        String pwd = (String) params.get("pwd");
        UserEntity userEntity = baseMapper.selectById(tel);

        if (userEntity!=null){
            if (userEntity.getPwd().equals(pwd)){
                String token = jwtUtil.createJWT(userEntity.getTel(), userEntity.getName(), "admin");
                return R.ok("登陆成功").put("code",0).put("token",token).put("name",userEntity.getName());
            }
            return R.error(500,"用户名或密码错误");
        }
        return R.error(500,"用户名或密码错误");
    }

    @Override
    public R add(UserEntity user) {
        //注册成功系统使用MQ异步通知优惠券系统，自动给用户发送满10.01元减10元的新人优惠券（4分）
        Integer code = (Integer) redisTemplate.boundValueOps(user.getTel()).get();
        if (!user.getCode().equals(code+"")){
            return R.error("验证码有误");
        }
        baseMapper.add(user);
        MydisEntity mydisEntity = new MydisEntity();
        mydisEntity.setName("满10.01元减10元的新人优惠券");
        mydisEntity.setCreateDate(new Date());
        mydisEntity.setType("无限制");
        mydisEntity.setState("未使用");
        mydisEntity.setTel(user.getTel());
        rabbitTemplate.convertAndSend("msg2",mydisEntity);

        return R.ok("注册成功");
    }

}